<template>
  <div class="equipment-types-page">
    <div class="search-wrapper">
      <div class="content-wrapper">
        <div class="add-btn-wrapper">
          <div class="add-btn" @click="addHandle">新增</div>
        </div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">设备类型列表</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
          v-loading="listApiLoading"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="name" label="类型名称" />
          <el-table-column label="操作" width="150" align="left">
            <template #default="scope">
              <span class="table-btn" @click="editHandle(scope.row)">编辑</span>
              <span class="table-btn" @click="deleteHandle(scope.row)"
                >删除</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      :title="isEdit ? '编辑设备类型' : '添加设备类型'"
      width="50%"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="设备类型" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入设备类型名称"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { typesAPI } from "@/api/service/equipmentManage";
import { addOrUpdateAPI, deleteAPI } from "@/api/service/device-types";

// 设备类型数据类型
interface EquipmentTypeType {
  id: string;
  name: string;
  description?: string;
  createTime?: string;
}

// 表格数据
const tableData = ref<EquipmentTypeType[]>([]);
// API调用保护状态
const listApiLoading = ref(false);

// 加载设备类型列表
const loadEquipmentTypeList = async () => {
  try {
    listApiLoading.value = true;
    const response = await typesAPI();
    const result = response as any;

    if (Array.isArray(result)) {
      tableData.value = result;
    } else if (result && Array.isArray(result.deviceTypes)) {
      tableData.value = result.deviceTypes;
    }
  } catch (error) {
    ElMessage.error("获取设备类型列表失败");
  } finally {
    listApiLoading.value = false;
  }
};

// 添加表单数据
const addForm = ref<any>({
  id: "",
  name: "",
});

// 表单验证规则
const addFormRules = {
  name: [{ required: true, message: "请输入设备类型名称", trigger: "blur" }],
};

// 添加设备类型
const addDialogVisible = ref(false);
const addFormRef = ref();
const addFormLoading = ref(false);
const isEdit = ref(false);

function addHandle() {
  isEdit.value = false;
  addDialogVisible.value = true;
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 编辑组织
function editHandle(row: any) {
  isEdit.value = true;
  addDialogVisible.value = true;
  addForm.value = {
    id: row.id,
    name: row.name,
  };
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 重置添加表单
function resetAddForm() {
  addForm.value = {
    id: "",
    name: "",
  };
  addFormRef.value?.clearValidate();
}

// 提交添加表单
function submitAddForm() {
  // 防止并发提交
  if (addFormLoading.value) return;

  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      addFormLoading.value = true;

      // 根据是否编辑调用不同的API
      const apiCall =
        isEdit.value && addForm.value.id
          ? addOrUpdateAPI({
              id: addForm.value.id,
              name: addForm.value.name,
            })
          : addOrUpdateAPI({
              name: addForm.value.name,
            });

      apiCall
        .then(() => {
          ElMessage.success(
            isEdit.value ? "编辑设备类型成功" : "添加设备类型成功"
          );
          addDialogVisible.value = false;
          resetAddForm();
          // 刷新列表
          loadEquipmentTypeList();
        })
        .catch(() => {
          ElMessage.error(
            isEdit.value ? "编辑设备类型失败" : "添加设备类型失败"
          );
        })
        .finally(() => {
          addFormLoading.value = false;
        });
    }
  });
}

// 删除组织
function deleteHandle(row: any) {
  ElMessageBox.confirm("确定删除该设备类型吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteAPI(row.id)
      .then(() => {
        ElMessage.success("删除设备类型成功");
        loadEquipmentTypeList();
      })
      .catch(() => {
        ElMessage.error("删除设备类型失败");
      });
  });
}

// 页面初始化
onMounted(() => {
  loadEquipmentTypeList();
});
</script>

<style scoped lang="scss">
.equipment-types-page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  background-color: #fff;
  flex-shrink: 0;
  padding: 1.5rem;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    justify-content: flex-end;
    flex-wrap: wrap;
    padding: 2rem 2rem 0 2rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    padding-right: 2rem;
    .item-label {
      display: inline;
      padding-right: 1rem;
      flex-wrap: nowrap;
      text-align: right;
      color: $text-color-regular;
    }
    .item-input {
      width: 20rem;
    }
  }
  .search-btn {
    display: flex;
    align-items: center;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
  .add-btn {
    display: flex;
    align-items: center;
    padding: 0.5rem 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    padding: 0 2rem;
    flex: 1;
    min-height: 0;
    margin-top: 1.5rem;
  }

  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
    &.disabled {
      background-color: $text-color-disabled;
      border: 1px solid $text-color-disabled;
      cursor: not-allowed;
    }
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
}
</style>
